const router = require('koa-router')()
const File = require('../models/file')
const multer = require('koa-multer')
const mkdirp = require('mkdirp')
const fs = require('fs')
const path = require('path')
let now = new Date(),
    currMonth = now.toISOString().substr(0, 7);
let dest = `uploads/${currMonth}/`;
let upload = multer({ dest: dest});
fs.existsSync(upload) ? '' : mkdirp.sync(path.join(__dirname,'../' ,dest))
router.prefix('/common')


/**
 * 上传文件
 * @type {[type]}
 */
router.post('/upload',  upload.array('files', 12), async (ctx, next) => {
  try {
    let files = ctx.req.files
      let f = [];
      for(let i= 0;i < files.length; i++) {
          let item = files[i]
          let ret = await File.create({savePath: item.path, fileName: item.filename, mimeType: item.mimetype, size: item.size, originalname: item.originalname, account: ctx.req.body.account})
          f.push({id: ret._id})
      }
      ctx.body = {code: 0, data: f}
  }catch(err) {
    ctx.body = {code: -1, errmsg: `upload file fail`}
  }
})


router.get('/downLoadFile', async (ctx, next) => {
  let {id} = ctx.query;
    let f = await File.findOne({_id: id});
    ctx.res.setHeader('Content-disposition', `attachment; filename=${encodeURIComponent(f.originalname)};filename*=utf-8${f.fileName}`);
    ctx.res.setHeader('Content-type', f.mimeType);
    f.size ? ctx.res.setHeader("Content-Length", Number(+f.size).toString()) : '';
    ctx.body = fs.createReadStream(path.resolve(process.env.dataDir, f.savePath));
})



module.exports = router
